local _G = _G
local LBF = LibStub("LibButtonFacade", true)
local elements = {"Earth", "Air", "Water", "Fire"}

function Yata:SetButtonSkin(skin)
	self.db.profile.ButtonSkin = skin or self.db.profile.ButtonSkin
	if LBF and self.LBFGroup then
		self.LBFGroup:Skin(skin,0,true)
	end
end

function Yata:SetAutoButtonSwap(autobutton)	
	self.db.profile.AutoButtonSwap = autobutton
	for i,b in ipairs(self.TotemButtons.Buttons) do
		b:SetOnClickScript(self.db.profile.AutoButtonSwap)
	end
end

function Yata:SetButtonSwapKey(key)
	self.db.profile.ButtonSwapKey = key or self.db.profile.ButtonSwapKey
	for i,b in ipairs(self.TotemButtons.Buttons) do
		b:SetAttribute("swapkey",self.db.profile.ButtonSwapKey)
	end
end

function Yata:SetButtonNoSwapKey(key)
	self.db.profile.ButtonNoSwapKey = key or self.db.profile.ButtonNoSwapKey
	for i,b in ipairs(self.TotemButtons.Buttons) do
		b:SetAttribute("noswapkey",self.db.profile.ButtonNoSwapKey)
	end
end

function Yata:SetBarConfiguration(gapValue, orientationValue, visibleValue)
	gapValue = gapValue or self.db.profile.ButtonGap
	orientationValue = orientationValue or self.db.profile.BarOrientation
	visibleValue = visibleValue or self.db.profile.VisibleButtons
	self.db.profile.ButtonGap = gapValue
	self.db.profile.BarOrientation = orientationValue
	self.db.profile.VisibleButtons = visibleValue
	if self.db.profile.ButtonSkin == "Blizzard" then
		gapValue = gapValue + 4
	end
	local buttonSize =  36 + gapValue
	local set = self:GetTotemSet()
	for k,v in ipairs(set.ElementsOrder) do
		local header = self.TotemButtons[v].Header
		header:SetAttribute("buttongap",gapValue)
		header:SetWidth(36)
		header:SetHeight(36)
		header:SetAttribute("visiblebuttons", visibleValue)
		header:SetAttribute("orientation",orientationValue)
		header:SetAttribute("position",k-1)
	end
	self.TotemBarGrip:SetWidth(#set.ElementsOrder * buttonSize)
	for k,v in ipairs(self.TotemButtons.Buttons) do
		if self.db.profile.ButtonSkin == "Blizzard" then
			v.Duration:SetPoint("TOP",v.Parent,"BOTTOM",0,-4)
		else
			v.Duration:SetPoint("TOP",v.Parent,"BOTTOM",0,0)
		end
	end
	self:SetTotemSet(nil,set)
	self:ChangeTotemSet(self.db.profile.CurrentTotemSet)
end

function Yata:SkinChanged(SkinID,Gloss,Backdrop,Group,Button,Colors)
	self.db.profile.ButtonSkin = SkinID
	self:SetBarConfiguration()
end

function Yata:CreateTotemBar()
	if LBF then
		self.LBFGroup = LBF:Group("Yata")
		self.LBFGroup.SkinID = self.db.profile.ButtonSkin
		LBF:RegisterSkinCallback("Yata",self.SkinChanged,self)		
	end	
	self:RegisterEvent("SPELL_UPDATE_COOLDOWN", "BarUpdateHandler")
	self.TotemBarGrip = Yata:CreateBarGrip()
	self.TotemButtons = {["Buttons"] = {},
							["Earth"] = { ["Header"] = nil, ["Buttons"] = {}, ["Proxy"] = nil}, 
							["Fire"] = {["Header"] = nil, ["Buttons"] = {}, ["Proxy"] = nil }, 
							["Water"] = {["Header"] = nil, ["Buttons"] = {}, ["Proxy"] = nil }, 
							["Air"] = {["Header"] = nil, ["Buttons"] = {}, ["Proxy"] = nil }}
	local set = self:GetTotemSet()
	for k,v in ipairs(set.ElementsOrder) do
		local header = Yata.Button:CreateHeader(v, self.TotemBarGrip)
		self.TotemButtons[v].Header = header
		local proxy = Yata.Button:CreateTotemProxy(v,self.TotemBarGrip)
		proxy:SetPoint("TOPLEFT",proxy.Parent,"TOPLEFT",-50,(k-1)*36)
		proxy:Hide();
		if LBF then
			proxy.LBFButtonData = {Button = proxy, Icon = proxy.Icon, HotKey = proxy.HotKey, Cooldown = proxy.Cooldown}
			self.LBFGroup:AddButton(proxy, proxy.LBFButtonData)				
		end				
		self.TotemButtons[v].Proxy = proxy
		for m,n in ipairs(set[v]) do
			local totem = Yata:GetTotem(n)			
			local button = Yata.Button:Create(totem.Name,self.TotemButtons[totem.Element].Header, totem)
			button.Icon:SetTexture(totem.Texture)  	
			button:SetAttribute("*type*", "spell")
			button:SetAttribute("*spell1", totem.Name)
			button:SetAttribute("spell2", GetSpellInfo(36936)) -- Totemic Call
			button:SetFrameRef("header",self.TotemButtons[totem.Element].Header)
			button:Execute([[header = self:GetFrameRef("header")]])	
			if LBF then
				button.LBFButtonData = {Button = button, Icon = button.Icon, HotKey = button.HotKey, Cooldown = button.Cooldown}
				self.LBFGroup:AddButton(button, button.LBFButtonData)				
			end		
			button:SetAttribute("position", m-1)
			table.insert(self.TotemButtons.Buttons, button)
			table.insert(self.TotemButtons[totem.Element].Buttons,button)
		end
	end
	self:SetProxyBinding()
	self:SetButtonSkin()
	self:SetBarConfiguration()
	self:SetButtonSwapKey()
	self:SetButtonNoSwapKey()
	self:SetAutoButtonSwap(self.db.profile.AutoButtonSwap)
end

function Yata:BarUpdateHandler()
	if self.db.profile.TimerType == 1 then
		local totem = Yata.TotemData[GetSpellInfo(8071)] -- Stoneskin Totem
		local spellId = totem[#totem].SpellID
		local start, duration, enable = GetSpellCooldown(spellId, BOOKTYPE_SPELL)
		for k,v in ipairs(self.TotemButtons.Buttons) do
			CooldownFrame_SetTimer(v.Cooldown, start, duration, enable)
		end
	end
end

function Yata:StartMoving()
	self.db.profile.Locked = false
	self.TotemBarGrip.Texture:Show()
	for k,v in ipairs(elements) do
		self.TotemButtons[v].Header:Hide()
	end
	self:ShowTimerAnchors()
end
function Yata:StopMoving()
	self.db.profile.Locked = true
	self.TotemBarGrip.Texture:Hide()
	self:SaveBarConfig()
	for k,v in ipairs(elements) do
		self.TotemButtons[v].Header:Show()
	end
	self:HideTimerAnchors()	
end


function Yata:CreateBarGrip()
	if _G["YataBarGrip"] then return _G["YataBarGrip"] end
	local grip = CreateFrame("Frame", "YataBarGrip", UIParent, "SecureFrameTemplate")
	grip.Name = "YataBarGrip"
	grip.Parent = UIParent
	grip:SetHeight(36)
	grip:SetWidth(0)
	grip.Texture = grip:CreateTexture()
	grip.Texture:SetTexture(0, 0, 0.5, 0.5)
	grip.Texture:SetAllPoints(grip)	
	grip:RegisterForDrag( "LeftButton" )
	grip:EnableMouse(true)
	grip:SetMovable(true)
	grip:SetScript("OnDragStart", function()
		if(not self.db.profile.Locked) then
			this:StartMoving()
		end
	end)
	grip:SetScript("OnDragStop", function()
		this:StopMovingOrSizing()
	end)	
	return grip
end

function Yata:ColorYata()
--[[
	local overlayFrame = Yata:GetOverlayFrame()
	if (Yata.keyBoundMode) then
		overlayFrame:SetBackdropColor(LibKeyBound:GetColorKeyBoundMode())
	elseif (Yata.someOtherMode) then
	end
	--]]
end

function Yata:LIBKEYBOUND_ENABLED()
	for i,b in ipairs(elements) do
		self.TotemButtons[b].Header:SetAttribute("visiblebuttons",10)
		self.TotemButtons[b].Header:SetAttribute("show",true)
		self.TotemButtons[b].Proxy:Show()
	end
	Yata.keyBoundMode = true
end

function Yata:LIBKEYBOUND_DISABLED()
	Yata.keyBoundMode = nil
	for i,b in ipairs(elements) do
		self.TotemButtons[b].Header:SetAttribute("visiblebuttons",self.db.profile.VisibleButtons)
		self.TotemButtons[b].Header:SetAttribute("show",false)
		self.TotemButtons[b].Proxy:Hide()
	end
	self:SetProxyBinding()
end

function Yata:SetProxyBinding()
	for i,b in ipairs(elements) do
		local key = GetBindingKey(format("CLICK %s:LeftButton", self.TotemButtons[b].Proxy.Name))
		self.TotemButtons[b].Header:SetAttribute("proxybinding",key)
	end
end

function Yata:LIBKEYBOUND_MODE_COLOR_CHANGED()
end


function Yata:SaveBarConfig()
	if not self.db.profile.BarPosition then 
		self.db.profile.BarPosition = {}
	end
	local scale = self.TotemBarGrip:GetEffectiveScale()
	scale = scale / self.db.profile.BarScale
	local x = self.TotemBarGrip:GetLeft()/scale
	local y = self.TotemBarGrip:GetBottom()/scale 
	self.db.profile.BarPosition.x = x
	self.db.profile.BarPosition.y = y
	self:SetTotemSet(nil,set)
	self:EditMacro(true,nil,nil)
	self:SetTotemSet(nil,nil)
end

function Yata:LoadBarConfig()
	if self.db.profile.Locked then
		self.TotemBarGrip.Texture:Hide()
	end	
	local x,y,scale
	if self.db.profile.BarPosition then
		scale = self.TotemBarGrip:GetEffectiveScale()	
		x = self.db.profile.BarPosition.x * scale
		y = self.db.profile.BarPosition.y * scale
	else
		self.TotemBarGrip:ClearAllPoints()
		self.TotemBarGrip:SetPoint( "CENTER", WorldFrame, "CENTER", 0,0 )
		scale = self.TotemBarGrip:GetEffectiveScale()
		x = self.TotemBarGrip:GetLeft()*scale
		y = self.TotemBarGrip:GetBottom()*scale
	end	
	self.TotemBarGrip:ClearAllPoints()
	self.TotemBarGrip:SetPoint("BOTTOMLEFT", UIParent,"BOTTOMLEFT", x, y)
	self.TotemBarGrip:SetScale(self.db.profile.BarScale)	
end

function Yata:EditMacro(force, old,new)
	local num = GetNumMacros()
	local macroindex = GetMacroIndexByName("YataTotemStomp")
	if force or macroindex == 0 and num < 36 then
		local macro = "#showtooltip\n/castsequence reset=combat/"..self.db.profile.MacroResetKey.." "
		local totems = {}
		local set = self:GetTotemSet()
		for k,v in ipairs(set.ElementsOrder) do
			for i,b in ipairs(self.TotemButtons[v].Buttons) do
				if b:GetAttribute("position") == 0 then
					table.insert(totems,b.Totem.Name)
					break
				end
			end
		end
		for k,v in ipairs(totems) do
			if totems[k] and totems[k+1] then
				macro = string.format("%s%s, ",macro,v)
			else
				macro = string.format("%s%s",macro,v)
			end
		end
		local numIcons = GetNumMacroIcons()
		local iconid = 0
		for i=1,numIcons do
			if GetMacroIconInfo(i) == "Interface\\Icons\\INV_Misc_QuestionMark" then
				iconid = i
				break
			end
		end	
		if force and macroindex > 0 then		
			EditMacro(macroindex, "YataTotemStomp", iconid, macro, 1)
		else
			CreateMacro("YataTotemStomp",iconid,macro,1,1)
		end
	elseif macroindex > 0 and old and new then
		local name, texture, macro, isLocal = GetMacroInfo(macroindex)
		macro = string.gsub(macro,old,new)
		EditMacro(macroindex, name, texture, macro, isLocal);
	end	
end

